package org.an.proj.contacts.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import link.config.AgentConfig;
import link.config.StoreConfig;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.config.Config;
import org.an.proj.contacts.config.LogUtil;

/**
 * 创建时间：2016年12月20日19:16 <br>
 * 作者：fuchaoyang <br>
 * 描述：
 */

public class AppUtil {

  /**
   * 获取当前进程名
   *
   * @param context context
   */
  public static String getCurProcessName(Context context) {
    int pid = android.os.Process.myPid();
    ActivityManager mActivityManager =
        (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
      if (appProcess.pid == pid) {
        return appProcess.processName;
      }
    }
    return null;
  }

  /**
   * 检验是否有权限
   *
   * @param permission 权限
   */
  public static boolean checkPermission(String permission) {
    return ActivityCompat.checkSelfPermission(MyApplication.getInstance(), permission)
        != PackageManager.PERMISSION_GRANTED;
  }

  /**
   * 获取http请求的UA:服务端对接口校验版本号是根据UA中的版本标识
   */
  public static String getUserAgent(@NonNull Context context, String channel) {
    String brand = "";
    String model = "";

    try {
      brand = URLEncoder.encode(Build.BRAND, "UTF-8");
      model = URLEncoder.encode(Build.MODEL, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    String ua = new StringBuffer().append(channel)
        .append(Config.VERSION_NAME)
        .append(";")
        .append(brand)
        .append(" ")
        .append(model)
        .append("; Android ")
        .append(Build.VERSION.RELEASE)
        .append(";appid=")
        .append(DeviceUtil.getUUID(context))
        .toString();
    LogUtil.e("UA", ua);
    return ua;
  }

  public static void startActivity(Class cls) {
    Intent intent = new Intent(MyApplication.getInstance(), cls);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MyApplication.getInstance().startActivity(intent);
  }

  /**
   * 登出
   */
  public static void logout() {
    StoreConfig.getInstance().setLogin(false);
    StoreConfig.getInstance().setConfigInfo(null);
    StoreConfig.getInstance().setToken(null);
    AgentConfig.getInstance().setAgentInfo(null);
  }
}
